package com.wlhse.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wlhse.cache.JedisClient;
import com.wlhse.dao.LoginIPadDao;
import com.wlhse.dto.outDto.UserInfoOutDto;
import com.wlhse.service.UserPingService;
import com.wlhse.util.GetIPUtil;
import com.wlhse.util.MD5Util;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserPingServiceImpl implements UserPingService {
    //dao
    @Resource
    private LoginIPadDao loginIPadDao;

    @Resource
    private UserInfoOutDto userInfoOutDto;

    @Resource
    private JedisClient jedisClient;

    @Override
    public String login(String name, String pwd, HttpServletRequest request) {
        String ip = GetIPUtil.getIpAddr(request);
        if (jedisClient.get(ip, 1) == null || Integer.parseInt(jedisClient.get(ip, 1)) < 5) {
            String MD5psw = MD5Util.getMD5(pwd);
            userInfoOutDto = loginIPadDao.testifyUser(name, MD5psw);
            JSONObject object = new JSONObject(true);
            List<UserInfoOutDto> list = new ArrayList<>();
            if (userInfoOutDto != null) {
                list.add(userInfoOutDto);
                object.put("serverVersion", "0.0.1");
                object.put("status", 1);
                object.put("message", "登录成功");
                object.put("data", list);
            } else {
                object.put("serverVersion", "0.0.1");
                object.put("status", 0);
                object.put("message", "登录失败");
                object.put("data", list);
                jedisClient.incr(ip, CodeDict.TWENTY_MINUTES, 1);
            }
            return object.toJSONString();
        } else {
            return NR.r(CodeDict.LOGIN_FAIL_MANY_TIMES, 0, 0, null, null, 0, 0);
        }
    }
}
